package app.dws;

import Bean.ExamBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;
import org.checkerframework.checker.units.qual.A;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.HashSet;

public class Dws_DwsExamTestPaperWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_DwsExamTestPaperWindow().init(
                4003,
                2,
                "Dws_DwsExamTestPaperWindow",
                Constant.TOPIC_DWD_EXAM_TEST
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {


        // 2. 转成一个 pojo---将所有paper_id一样的同学放到一个相同的分区中，将其封装到一个Exambean中，
        stream
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        return value!=null;
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((obj,ts)->obj.getLong("ts")*1000))
                .keyBy(value -> value.getString("paper_id"))
                .process(new KeyedProcessFunction<String, JSONObject, ExamBean>() {

                    private ValueState<String> lastDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastDate", String.class));
                    }
                    @Override
                    public void processElement(JSONObject value,
                                               Context ctx,
                                               Collector<ExamBean> out) throws Exception {
                        Long ts = value.getLong("ts")*1000;
                        String lastdate = lastDate.value();
                        String today = AtguiguUtil.toDate(ts);
                        String paperId = value.getString("paper_id");
                        String userId = value.getString("user_id");
                        BigDecimal score = value.getBigDecimal("score");
                        BigDecimal durationSec = value.getBigDecimal("duration_sec");

                        if (!today.equals(lastdate)) {
                            lastDate.update(today);
                            out.collect(new ExamBean("","",
                                                    paperId,userId,1L

                                    ,score,durationSec,ts));
                        }

                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<ExamBean>() {
                            @Override
                            public ExamBean reduce(ExamBean value1,
                                                   ExamBean value2) throws Exception {
                                value1.setSumExamCt(value1.getSumExamCt()+value2.getSumExamCt());
                                value1.setAvgExamTime(value1.getAvgExamTime().add(value2.getAvgExamTime()));
                                value1.setAvgScore(value1.getAvgExamTime().add(value2.getAvgExamTime()));
                                return value1;
                            }
                        },
                        new AllWindowFunction<ExamBean, ExamBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window, 
                                              Iterable<ExamBean> values,
                                              Collector<ExamBean> out) throws Exception {
                                ExamBean bean = values.iterator().next();
                                bean.setStt(AtguiguUtil.toDatTime(window.getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(window.getEnd()));
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);

                            }
                        })
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_exam_test_paper_uu_window",ExamBean.class));


        // 3. 开窗聚和
        // 4. 写出到 clickhouse 中

//        process-->map--->watermark-->keyby--->window--->reduce
    }


    }

